#include "game.h"
#include "globals.h"
#include "graphics.h"
#include "constants.h"
#include "network.h"
#include "packetstream.h"
#include "connect.h"
#include "characters.h"
#include "mainmenu.h"

// Initializes the state
bool MainMenuState::Show() 
{
	int DrawX = 400, DrawY = 250, OffsetY = 50;

	// Single Player
	GraphicsClass::Instance().SetFont(GraphicsClass::FONT_10);
	IGUIButton *SinglePlayerButton = irrGUI->addButton(GraphicsClass::Instance().GetCenteredRect(DrawX, DrawY, 100, 25), 0, ELEMENT_SINGLEPLAYER, L"Single Player");

	// Multiplayer
	DrawY += OffsetY;
	IGUIButton *MultiplayerButton = irrGUI->addButton(GraphicsClass::Instance().GetCenteredRect(DrawX, DrawY, 100, 25), 0, ELEMENT_MULTIPLAYER, L"Multiplayer");

	// Options
	DrawY += OffsetY;
	IGUIButton *OptionButton = irrGUI->addButton(GraphicsClass::Instance().GetCenteredRect(DrawX, DrawY, 100, 25), 0, ELEMENT_OPTIONS, L"Options");
	OptionButton->setEnabled(false);

	// Exit
	DrawY += OffsetY;
	IGUIButton *ExitButton = irrGUI->addButton(GraphicsClass::Instance().GetCenteredRect(DrawX, DrawY, 100, 25), 0, ELEMENT_EXIT, L"Exit");

	// Game version
	GraphicsClass::Instance().AddText(GAME_VERSION, 10, 580);

	CGame::Instance().StopLocalServer();

	return true;
}

// Shuts the state down
bool MainMenuState::Hide() 
{
	return true;
}

// Updates the current state
void MainMenuState::Update(u32 TDeltaTime) 
{

}

// Draws the current state
void MainMenuState::Draw() 
{
	GraphicsClass::Instance().DrawImage(GraphicsClass::IMAGE_MENULOGO, 400, 125);
	irrGUI->drawAll();
}

// Key presses
bool MainMenuState::HandleKeyPress(EKEY_CODE TKey) 
{
	switch(TKey) 
	{
		case KEY_ESCAPE:
			CGame::Instance().Exit();
		break;
		case KEY_RETURN:
			StartSinglePlayer();
		break;
	}
	return false;
}

// GUI events
void MainMenuState::HandleGUI(EGUI_EVENT_TYPE TEventType, IGUIElement *TElement) 
{
	switch(TEventType) 
	{
		case EGET_BUTTON_CLICKED:
			switch(TElement->getID()) {
				case ELEMENT_SINGLEPLAYER:
					CGame::Instance().SwitchState("GS_CONNECT");
					StartSinglePlayer();
				break;
				case ELEMENT_MULTIPLAYER:
					CGame::Instance().SwitchState("GS_CONNECT");
				break;
				case ELEMENT_OPTIONS:
				break;
				case ELEMENT_EXIT:
					CGame::Instance().Exit();
				break;
			}
		break;
	}
}

// Starts a single player game
void MainMenuState::StartSinglePlayer() 
{
	CGame::Instance().StartLocalServer();
	CGame::Instance().Connect("");

	// Send fake account information
	PacketClass Packet(NetworkClass::ACCOUNT_LOGININFO);
	Packet.WriteBit(0);
	Packet.WriteString("singleplayer");
	Packet.WriteString("singleplayer");
	CGame::Instance().SendPacketToHost(&Packet);
	CGame::Instance().SwitchState("GS_CHARACTER");
}
